<template>
	<div class="app-quick-group">
		<span
			:class="getClassNames(item)"
			v-for="item in showItems"
			:key="item.value"
			:style="{ color: item.color }"
			@click="handleClick(item)"
		>
			<img v-if="item.icon" :src="item.icon" />
			<span class="app-quick-group-item__label">{{ item.text }}</span>
		</span>
	</div>
</template>
<script setup lang="ts">
import { ICodeListItem, ICodeListResult } from '@/core';
import { Ref } from 'vue';
import { quickGroupProps, getDefaultSelect } from './quick-group';
const props = defineProps(quickGroupProps);
const emit = defineEmits<{
	(name: 'valueChange', item: ICodeListItem): void;
}>();
//  数据
const showItems: Ref<ICodeListItem[]> = ref([]);

const selectItem: Ref<ICodeListItem | null> = ref(null);
const handleByCodeList = () => {
	if (!props.codeListTag) {
		console.warn(App.ts('common.generic.codelistnoconfig', '未配置代码表'));
	}
	App.getAppCodeListHelper()
		.getCodeListItems(
			props.codeListTag as string,
			props.context,
			props.viewParams
		)
		.then((response: ICodeListResult) => {
			if (response.ok && response.data.length > 0) {
				const defaultItem = getDefaultSelect(response.data);
				showItems.value.length = 0;
				showItems.value.push(...response.data);
				handleClick(defaultItem ? defaultItem : showItems.value[0]);
			}
		});
};

const isSelect = (item: ICodeListItem): boolean => {
	return !!(selectItem.value && selectItem.value.value === item.value);
};

const handleClick = (item: ICodeListItem) => {
	if (isSelect(item)) {
		return;
	}
	selectItem.value = item;
	emit('valueChange', selectItem.value);
};

const getClassNames = (item: ICodeListItem) => {
	return {
		'app-quick-group-item': true,
		'app-quick-group-item--selected':
			selectItem.value && selectItem.value.value === item.value,
	};
};

const handleByItems = () => {};
const init = () => {
	if (props.type === 'CODELIST') {
		handleByCodeList();
	} else if (props.type === 'ITEMS') {
		handleByItems();
	}
};
init();
</script>
